package nio;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/25 15:24
 */
public class NonBlockingNIOTest {

    // 客户端
    public static void main(String[] args) {
        // 1.获取通道
        try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898))) {
            // 2.切换非阻塞模式
            socketChannel.configureBlocking(false);
            // 3.分配指定大小的缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            System.out.println("input(exit:q):");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String readin = scanner.nextLine();
                if ("q".equalsIgnoreCase(readin)) {
                    System.out.println("Bye~");
                    break;
                }
                // 4.发送数据给服务器
                String msg = "[" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) +
                        "]:" + readin;
                buffer.put(msg.getBytes());
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
                System.out.println("send message over");
                System.out.println("input(exit:q):");
            }
            // 5.关闭通道
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 服务端
    @Test
    public void testServer() {
        // 1.获取通道
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            // 2.切换为非阻塞模式
            serverSocketChannel.configureBlocking(false);
            // 3.绑定连接
            serverSocketChannel.bind(new InetSocketAddress(9898));

            // 4.获取选择器
            Selector selector = Selector.open();

            // 5.将通道注册到选择器上，指定监听事件为接收事件
            // 接收事件为SelectionKey中定义的四个常量
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            // 6.轮询式的获取选择器上已经准备就绪的事件
            while (selector.select() > 0) {
                // 7.获取当前选择器中所有注册的选择键（已经就绪的监听事件）
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                while (iterator.hasNext()) {
                    // 8.获取准备就绪的事件
                    SelectionKey key = iterator.next();

                    // 9.判断具体是什么事件准备就绪
                    if (key.isAcceptable()) {
                        // 10. 若接收就绪，获取客户端连接
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        // 11.切换非阻塞模式
                        socketChannel.configureBlocking(false);
                        // 12.将通道注册到选择器上
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } else if (key.isReadable()) {
                        // 13.获取当前选择器上读就绪状态的通道
                        SocketChannel socketChannel = (SocketChannel) key.channel();

                        // 14. 读取数据
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int len = 0;
                        StringBuilder builder = new StringBuilder();
                        while ((len = socketChannel.read(buffer)) > 0) {
                            buffer.flip();
                            builder.append(new String(buffer.array(), 0, len));
                            buffer.clear();
                        }
                        if (StringUtils.isNoneEmpty(builder)) {
                            System.out.println(builder);
                        }
                    }
                    // 15. 取消选择键SelectionKey
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
